# -*- encoding: utf-8 -*-
from django.db import models
from django.contrib.sitemaps import ping_google
from django.conf import settings
from django.utils.translation import get_language

from modulo.utils import APPS
import mptt
from multilingual.translation import Translation
from multilingual.languages import get_translated_field_alias

from hashlib import sha1

# Always use lazy translations in Django models
from django.utils.translation import ugettext_lazy as _

class Section(models.Model):
    app         = models.CharField(_(u'app'),
                                   choices=APPS,
                                   max_length=31,
                                   help_text=_(u"Select the app to use with this section"),
                                   default='page')
    parent        = models.ForeignKey('self',
                                      null=True,
                                      blank=True,
                                      related_name='children',
                                      help_text=_(u"Select the place to add this section."))
    last_modif    = models.DateField(_('last modification'),
                                     auto_now=True)

    class Translation(Translation):
        title = models.CharField(_(u'title'),
                                 max_length=255,
                                 help_text = _(u'Title of the section'))
        slug = models.SlugField(_(u'slug'),
                                unique=True,
                                help_text=_(u'The section\'s URL. As to be meanful and contains only ASCII'))
        menuTop = models.BooleanField(_(u'Main menu'),
                                      help_text=_(u"Check if you want to display this section in the main menu ?"))
        orderTop = models.IntegerField(_(u"Ordre des onglets"),
                                       editable = False,
                                       default = 0)
        titleTop = models.CharField(_(u"Main menu title"),
                                    max_length=50,
                                    blank=True)

        menuLeft = models.BooleanField(_(u'Left menu'),
                                      help_text=_(u"Check if you want to display this section in the secondary menu ?"))
        orderLeft = models.IntegerField(_(u"Ordre des liens"),
                                       editable = False,
                                       default = 0)
        titleLeft = models.CharField(_(u"Left menu title"),
                                     max_length=50,
                                     blank=True)

        content   =  models.TextField(_(u'content'),
                                      blank=True)
        sha1      =  models.CharField(u'SHA1 Path ID',
                                      max_length=40,
                                      editable=False,
                                      db_index=True)

        def save(self):
            path = Section.objects.get(pk=self.master_id).path(self.slug,self.language_code)
            self.sha1 = sha1(path).hexdigest()

            if self.menuTop and self.orderTop == 0:
                self.orderTop = Section.objects.filter(menuTop__exact=1).count()+1

            if self.menuLeft and self.orderLeft == 0:
                self.orderLeft = Section.objects.filter(menuLeft__exact=1,parent=self.master_id).count()+1

            super(Section.Translation, self).save()

        def delete(self):
            super(Section.Translation, self).save()

            menusTop = Section.objects.filter(level__exact=0).filter(menuTop=True).exclude(title__exact='').order_by('orderTop')

            i = 1
            for m in menusTop:
                m.orderTop = i
                m.save()
                i += 1


            menusLeft = Section.objects.filter(parent=self.master_id, menuLeft=True).exclude(title__exact='').order_by('orderLeft')

            i = 1
            for m in menusLeft:
                m.orderLeft = i
                m.save()
                i += 1


    def path(self, last_slug=None, language_code=None):
        if not last_slug:
            last_slug = self.slug

        if language_code is None:
            language_code = get_language()

        parents = self.get_ancestors()
        items = []
        
        field_alias = get_translated_field_alias('slug', language_code)
        
            
        for a in parents:
            slug = getattr(a, field_alias, None)
            if slug is not None:
                items.append(slug)
            
        items.append(last_slug)

        return u'/%s/' % (u'/'.join(items))

    def __unicode__(self):
        return u'%s' % (self.title)

    def get_absolute_url(self):
        return self.path()

    def save(self, force_insert=False, force_update=False):
        super(Section, self).save(force_insert, force_update)
        if not settings.DEBUG:
            try:
                ping_google()
            except Exception:
                # We could have a variety of HTTP-related exceptions
                # and we don't care
                pass

    class Meta:
        ordering = ['level']

mptt.register(Section)

class Widget(models.Model):
    section = models.ForeignKey(Section,
                                related_name='widgets',
                                null=True,
                                blank=True,
                                help_text=_(u'Select the host page'))

    class Translation(Translation):
        slug = models.SlugField(u'Slug')
        title = models.CharField(_(u"title"),
                                 max_length=100)
        content = models.TextField(_(u'content'))
        link = models.CharField(_(u'URL'),
                                max_length=256,
                                help_text=_(u"/slug/ for a local link or http://www.url.com/ for an external link."),blank=True)


    class Meta:
        verbose_name = _(u"Fixed block content")
        verbose_name = _(u"Fixed blocks content")

    def __unicode__(self):
        return u'%s' % self.title

